package com.zhima.task;

import com.zhima.util.FileUtil;
import com.zhima.util.LanguageExecutor;

import javax.swing.*;
import java.io.*;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;

import static com.zhima.util.StrUtil.removeNewLine;

/**
 * @author : 芝麻
 * @date : 2023-08-05 13:44
 **/
public class GenerateOutDataTask implements Runnable {
    private final JLabel baseDirPathJLabel;
    private String codeFilePath;
    private final JTextField dataBarsNumberJTextField;
    private final ExecutorService executorService;

    public GenerateOutDataTask(ExecutorService executorService, JTextField dataBarsNumberJTextField, JLabel baseDirPathJLabel, String codeFilePath) {
        this.baseDirPathJLabel = baseDirPathJLabel;
        this.codeFilePath = codeFilePath;
        this.dataBarsNumberJTextField = dataBarsNumberJTextField;
        this.executorService = executorService;
    }

    @Override
    public void run() {
        codeFilePath = removeNewLine(codeFilePath);
        String suffix = codeFilePath.substring(codeFilePath.lastIndexOf(".") + 1);
        String baseDirPath = removeNewLine(baseDirPathJLabel.getText());
        int dataBarsNumber = Integer.parseInt(dataBarsNumberJTextField.getText());
        AtomicReference<String> fileNeedToDelete = new AtomicReference<>("");
        CountDownLatch countDownLatch = new CountDownLatch(dataBarsNumber);
        for (int i = 1; i <= dataBarsNumber; i++) {
            int finalI = i;
            executorService.submit(()->{
                String inFile = String.format("%s%stest%d.in", baseDirPath, File.separator, finalI);
                if (!FileUtil.exists(inFile)) {
                    countDownLatch.countDown();
                    return;
                }
                try (
                        BufferedReader br = new BufferedReader(new FileReader(inFile));
                        BufferedWriter bw = new BufferedWriter(new FileWriter(String.format("%s%stest%d.out", baseDirPath, File.separator, finalI)))
                ) {
                    List<String> result = LanguageExecutor.Language
                            .valueOf(suffix.toUpperCase(Locale.ROOT))
                            .runCode(codeFilePath, FileUtil.readFile(br));
                    fileNeedToDelete.set(result.remove(result.size() - 1));
                    for (String r : result) {
                        bw.write(r);
                        bw.write('\n');
                    }
                    bw.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    // 确保计数器
                    countDownLatch.countDown();
                }
            });
        }
        try {
            // 等待所有的生成任务完成，默认一直等待
            // TODO: 这里的超时时间要不要反转给用户来控制
            countDownLatch.await();
            // 删除编译后的文件 if exists
            FileUtil.deleteFileIfExists(fileNeedToDelete.get());
            JOptionPane.showMessageDialog(null, "输出数据生成完毕！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
